import sys
import threading
import os
from PySide6.QtWidgets import QApplication, QMainWindow
from PySide6.QtWebEngineWidgets import QWebEngineView
from PySide6.QtWebEngineCore import QWebEngineSettings, QWebEngineProfile, QWebEnginePage
from PySide6.QtCore import QUrl, Qt
from PySide6.QtGui import QSurfaceFormat, QIcon

from core.server import create_app

# 设置环境变量以启用GPU加速和Blink特性
os.environ["QTWEBENGINE_CHROMIUM_FLAGS"] = (
    "--enable-gpu-rasterization "
    "--enable-zero-copy "
    "--ignore-gpu-blocklist "
    "--disable-gpu-vsync "
    "--disable-frame-rate-limit "
    "--enable-accelerated-2d-canvas "
    "--enable-native-gpu-memory-buffers "
    "--enable-gpu-memory-buffer-compositor-resources "
    "--enable-oop-rasterization "
)

class CustomWebPage(QWebEnginePage):
    def javaScriptConsoleMessage(self, level, message, line, source):
        # 忽略JavaScript控制台消息，提高性能
        pass

class MainWindow(QMainWindow):
    def __init__(self, app):
        super().__init__()
        self.setWindowTitle("StudyAtAI")
        self.setGeometry(100, 100, 1280, 800)
        
        # 设置应用图标
        icon_path = os.path.join(os.path.dirname(__file__), 'static', 'images', 'app-icon.png')
        if os.path.exists(icon_path):
            app.setWindowIcon(QIcon(icon_path))
            self.setWindowIcon(QIcon(icon_path))
        
        # 创建WebEngine视图
        self.web_view = QWebEngineView()
        
        # 创建自定义页面
        self.web_page = CustomWebPage()
        self.web_view.setPage(self.web_page)
        
        # 获取默认配置文件并设置
        profile = QWebEngineProfile.defaultProfile()
        profile.setHttpCacheType(QWebEngineProfile.MemoryHttpCache)  # 使用内存缓存
        profile.setHttpCacheMaximumSize(100 * 1024 * 1024)  # 100MB 缓存
        profile.setPersistentStoragePath("./cache")  # 设置持久存储路径
        
        # 优化渲染设置
        settings = self.web_view.settings()
        
        # 启用硬件加速特性
        settings.setAttribute(QWebEngineSettings.WebGLEnabled, True)  # 启用WebGL
        settings.setAttribute(QWebEngineSettings.Accelerated2dCanvasEnabled, True)  # 启用2D加速
        settings.setAttribute(QWebEngineSettings.ScrollAnimatorEnabled, True)  # 启用平滑滚动
        
        # 内存和缓存优化
        settings.setAttribute(QWebEngineSettings.LocalStorageEnabled, True)
        settings.setAttribute(QWebEngineSettings.DnsPrefetchEnabled, True)  # 启用DNS预取
        
        # JavaScript优化
        settings.setAttribute(QWebEngineSettings.JavascriptEnabled, True)
        settings.setAttribute(QWebEngineSettings.JavascriptCanOpenWindows, True)
        settings.setAttribute(QWebEngineSettings.LocalContentCanAccessRemoteUrls, True)
        
        # 禁用不必要的功能
        settings.setAttribute(QWebEngineSettings.ErrorPageEnabled, False)
        settings.setAttribute(QWebEngineSettings.PluginsEnabled, False)
        settings.setAttribute(QWebEngineSettings.PdfViewerEnabled, False)
        settings.setAttribute(QWebEngineSettings.AutoLoadIconsForPage, False)
        
        # 设置页面
        self.web_view.setUrl(QUrl("http://localhost:5000"))
        self.setCentralWidget(self.web_view)
        
        # 优化窗口设置
        self.setWindowFlags(Qt.Window | Qt.WindowMinMaxButtonsHint | Qt.WindowCloseButtonHint)
        self.setAttribute(Qt.WA_TranslucentBackground, False)  # 禁用透明度
        self.setAttribute(Qt.WA_OpaquePaintEvent, True)  # 启用不透明绘制

def start_flask():
    """在新线程中启动Flask服务器"""
    flask_app = create_app()
    # 禁用重载器和调试模式
    flask_app.run(host='localhost', port=5000, use_reloader=False, debug=False, threaded=True)

def main():
    # 设置OpenGL格式
    gl_format = QSurfaceFormat()
    gl_format.setRenderableType(QSurfaceFormat.OpenGL)
    gl_format.setProfile(QSurfaceFormat.CoreProfile)
    gl_format.setSwapBehavior(QSurfaceFormat.DoubleBuffer)
    gl_format.setSwapInterval(0)  # 禁用垂直同步
    QSurfaceFormat.setDefaultFormat(gl_format)
    
    # 在创建QApplication之前设置属性
    QApplication.setAttribute(Qt.AA_ShareOpenGLContexts)
    QApplication.setAttribute(Qt.AA_UseDesktopOpenGL)  # 优先使用桌面OpenGL
    QApplication.setAttribute(Qt.AA_CompressHighFrequencyEvents)  # 压缩高频事件
    
    # 启动Qt应用
    app = QApplication(sys.argv)
    
    # 启动Flask服务器
    flask_thread = threading.Thread(target=start_flask)
    flask_thread.daemon = True
    flask_thread.start()
    
    # 创建并显示主窗口
    window = MainWindow(app)
    window.show()
    
    sys.exit(app.exec())

if __name__ == "__main__":
    main() 